package spring.datasource;

import java.sql.Connection;

public class ConnectionHolder {

    private Connection currentConnection;

    private ConnectionHandle connectionHandle;

    private int referenceCount = 0;

    public void requested() {
        this.referenceCount++;
    }

    public void released() {
        referenceCount--;
        if (referenceCount == 0 && this.currentConnection != null) {
            if (this.connectionHandle != null) {
                this.connectionHandle.releaseConnection(this.currentConnection);
            }
            this.currentConnection = null;
        }
    }

    public Connection getConnection() {
        if (this.currentConnection == null) {
            this.currentConnection = this.connectionHandle.getConnection();
        }
        return this.currentConnection;
    }

    protected void setConnection(Connection connection) {
        if (this.currentConnection != null) {
            if (this.connectionHandle != null) {
                this.connectionHandle.releaseConnection(this.currentConnection);
            }
            this.currentConnection = null;
        }
        if (connection != null) {
            this.connectionHandle = new SimpleConnectionHandle(connection);
        } else {
            this.connectionHandle = null;
        }
    }

    /**
     * Return whether this holder currently has a Connection.
     */
    protected boolean hasConnection() {
        return (this.connectionHandle != null);
    }

}
